<?php
namespace Home\Model;
use Think\Model;

/**
 * 本表记录支付平台返回信息，并没有别的卵用
CREATE TABLE art_pay(
id INT(8) NOT NULL PRIMARY KEY AUTO_INCREMENT,
orderno INT(20) NOT NULL,
orderdate varchar(45) NOT NULL,
amount FLOAT(6,2) NOT NULL,
jylsh VARCHAR(45) NOT NULL,
tranStat INT(8) NOT NULL,
isreturn INT(8) default 0,
isnotify INT(8) default 0
);
*/

class PayModel extends Model{
    private $_id;    // 本系统内支付信息唯一标识号
    private $_orderno;   // 支付订单号，本系统内采用的是Enroll的id
    private $_orderdate; // 支付日期，为支付系统传递过来的
    private $_amount;    // 支付金额
    private $_jylsh; // 支付平台交易流水号
    private $_tranStat;  // 支付状态，1标示成功
    private $_isreturn;  // 是否已经返回页面
    private $_isnotify;  // 是否已经通知服务器
    public function saveOne($data){
        $this->_orderno = $data['orderNo'];
        $this->_orderdate = $data['orderDate'];
        $this->_amount = $data['amount'];
        $this->_jylsh = $data['jylsh'];
        $this->_tranStat = $data['tranStat'];
        $id = $this->isHas();
        if($id === false){
            $this->_isnotify = $data['return_type'] == 2 ? 1 : 0;
            $this->_isreturn = $data['return_type'] == 1 ? 1 : 0;
            return $this->add($this->convert_data(false));
        }else{
            $this->_id = $id;
            if($this->_isnotify != 1){
                $this->_isnotify = $data['return_type'] == 2 ? 1 : 0;
            }
            if($this->_isreturn != 1){
                $this->_isreturn = $data['return_type'] == 1 ? 1 : 0;
            }
            return $this->save($this->convert_data(true));
        }
    }

    private function convert_data($needid){
        $data = array();
        if($needid == true){
            $data['id'] = $this->_id;
        }
        $data['orderno'] = $this->_orderno;
        $data['orderdate'] = $this->_orderdate;
        $data['amount'] = $this->_amount;
        $data['jylsh'] = $this->_jylsh;
        $data['tranStat'] = $this->_tranStat;
        $data['isreturn'] = $this->_isreturn;
        $data['isnotify'] = $this->_isnotify;
        return $data;
    }

    private function isHas(){
        $info = $this->where(array('orderno'=>$this->orderno))->find();
        if(empty($info))return false;
        $this->_isreturn = $info['isreturn'];
        $this->_isnotify = $info['isnotify'];
        return $info['id'];
    }
}
